package com.unknowpupil.task;


import com.unknowpupil.service.HealthService;
import com.unknowpupil.utils.DateUtils;
import com.unknowpupil.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;


/**
 * Created at 2020/11/4 by w10g <br>
 * Initialize ScheduldeTask ... <br>
 *
 * @author unknowpupil
 * @since 0.0.1
 */
@Slf4j
@Component      //1.主要用于标记配置类，兼备Component的效果。
public class ScheduldeTask {
    @Autowired
    HealthService healthService;

    @Scheduled(cron = "30 * * * * ?")
//    或直接指定时间间隔，例如：5秒
//    @Scheduled(fixedRate=5000)
    private void configureTasks() {
        log.info("执行时间：{}", DateUtils.dateToStr(new Date()));
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet("http://www.cqdtjc.cn/");
        try {
            HttpResponse response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println(statusCode);

            httpGet.releaseConnection();
        } catch (IOException e) {
            log.error("无法连接请求，错误原因{}", e.getMessage());
            Runtime runtime = Runtime.getRuntime();
            try {
                runtime.exec("/usr/local/nginx/sbin/nginx");
                log.info("nginx -------------- 重启成功");
            } catch (IOException ex) {
                log.error("nginx -------------- 重启失败，错误原因{}", ex.getMessage());
            }

            healthService.nginxMessage(e.getMessage());
        }

    }
}
